package com.supor.aiot.food.ui.food;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.android.baseconfig.base.BaseActivity;
import com.android.baseconfig.base.BasePresenter;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.ClearEditText;
import com.android.baseconfig.common.views.CustomTitleBar;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.food.R;
import com.supor.aiot.food.adapter.RecipeHotAdapter;
import com.supor.aiot.food.adapter.RecipeTagsAdapter;
import com.supor.aiot.food.api.SearchFoodImpl;
import com.supor.aiot.food.bean.ChildList;
import com.supor.aiot.food.bean.ChildListBean;
import com.supor.aiot.food.bean.RecipeHotBean;
import com.supor.aiot.food.bean.RecipeStoreBean;
import com.supor.aiot.food.view.GrideDecoration;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

public class RecipeTagsActivity extends BaseActivity implements TextView.OnEditorActionListener, TextWatcher {

    CustomTitleBar toolbar;
    RecyclerView rvRecipeTitle;
    SwipeRecyclerView rvRecipeDetail;
    SmartRefreshLayout refreshLayout;
    //    RelativeLayout rlNoneResult;
    ClearEditText clearEditText;
    private int originPosition;
    private String recipeId;
    private String deviceModel;
    private String deviceName;
    private List<ChildList> classifyList = new ArrayList<>();
    private ChildListBean childListBean;
    private List<RecipeHotBean> mHotList = new ArrayList<>();
    private RecipeTagsAdapter recipeTagsAdapter;
    private RecipeHotAdapter hotAdapter;
    private int originPage = 1;
    private boolean isUserControl = false;
    private static final String CLASSIFY_SECOND_DATA = "CLASSIFY_SECOND_DATA";
    private static final String CLASSIFY_SECOND_POSITION = "CLASSIFY_SECOND_POSITION";
    private static final String CHEF_ID = "CHEF_ID";
    private static final String DEVICE_RECIPE = "DEVICE_RECIPE";
    private static final String DEVICE_RECIPE_NAME = "DEVICE_RECIPE_NAME";
    private static final String SEARCH_KEYWORD = "SEARCH_KEYWORD";
    private Long lastSearchTime;
    private int code = 1000;
    private String recomondWord;
    private LinearLayout llSkeleton;
    private TextView tvNoneResult;

    @Override
    protected int resourceId() {
        return R.layout.activity_recipes;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(resourceId());
        ButterKnife.bind(this);
        initView();
        initClassifyData();
        initRecycleView();
    }

    @Override
    protected void initView() {
        super.initView();
        toolbar = findViewById(R.id.recipe_titlebar);
        rvRecipeTitle = findViewById(R.id.rv_recipe_title);
        rvRecipeDetail = findViewById(R.id.rv_recipe_detail);
//        rlNoneResult = findViewById(R.id.rl_none_result);
        llSkeleton = findViewById(R.id.ll_skeleton);
        tvNoneResult = findViewById(R.id.tv_none_result);
        clearEditText = findViewById(R.id.edt_common_search);

        toolbar.setIvLeftOnClickListener(view -> RecipeTagsActivity.this.finish());
        originPosition = getIntent().getIntExtra(CLASSIFY_SECOND_POSITION, 0);
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            originPage++;
            if (!TextUtils.isEmpty(deviceModel)) {
                getDeviceRecipe(deviceModel);
            } else {
                initSecondClassify(recipeId);
            }
        });
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        clearEditText.setOnEditorActionListener(this);
        clearEditText.addTextChangedListener(this);
    }

    @SuppressLint("AutoDispose")
    private void initSecondClassify(String id) {
        if (originPage == 1 && mHotList.size() == 0) {
            llSkeleton.setVisibility(View.VISIBLE);
        } else {
            llSkeleton.setVisibility(View.GONE);
        }

        SearchFoodImpl.getInstance().checkRecipeClassify(id, originPage, 10).subscribe(result -> {
            if (originPage == 1) mHotList.clear();
            if (mHotList.size() < result.data.getTotal()) {
                mHotList.addAll(result.data.rows);
            }
            llSkeleton.setVisibility(View.GONE);
            if (mHotList.size() > 0) {
                tvNoneResult.setVisibility(View.GONE);
                refreshLayout.setVisibility(View.VISIBLE);
            } else {
                tvNoneResult.setVisibility(View.VISIBLE);
                refreshLayout.setVisibility(View.GONE);
            }
            hotAdapter.notifyDataSetChanged();
            refreshLayout.finishLoadMore();
            if (mHotList.size() < 10) refreshLayout.setEnableLoadMore(false);
        }, throwable -> {
            Log.e(TAG, "classify recipe查询失败: " + throwable.getMessage());
            refreshLayout.finishLoadMore();
        });
    }

    @SuppressLint("AutoDispose")
    private void getDeviceRecipe(String deviceModel) {
        if (originPage == 1 && mHotList.size() == 0) {
            llSkeleton.setVisibility(View.VISIBLE);
        } else {
            llSkeleton.setVisibility(View.GONE);
        }
        SearchFoodImpl.getInstance().getNewRecipeByProduct(deviceModel, originPage, 10).subscribe(result -> {
            if (originPage == 1) mHotList.clear();
            if (mHotList.size() < result.data.getTotal()) {
                mHotList.addAll(result.data.rows);
            }
            llSkeleton.setVisibility(View.GONE);
            if (mHotList.size() > 0) {
                tvNoneResult.setVisibility(View.GONE);
                refreshLayout.setVisibility(View.VISIBLE);
                recomondWord = mHotList.get(0).getRecipeName();
                clearEditText.setHint(recomondWord);
            } else {
                tvNoneResult.setVisibility(View.VISIBLE);
                refreshLayout.setVisibility(View.GONE);
                initNewRecomond();
            }
            hotAdapter.notifyDataSetChanged();
            refreshLayout.finishLoadMore();
            if (mHotList.size() < 10) refreshLayout.setEnableLoadMore(false);
        }, throwable -> {
            Log.e(TAG, "classify recipe查询失败: " + throwable.getMessage());
            refreshLayout.finishLoadMore();
        });
    }

    /**
     * 收藏食谱
     *
     * @param storeBean
     */
    @SuppressLint("AutoDispose")
    private void setRecipeStored(RecipeStoreBean storeBean) {
        SearchFoodImpl.getInstance().recipeStore(storeBean).subscribe(result -> {
            if (result.isSuccess()) {
                if (!TextUtils.isEmpty(deviceModel)) {
                    getDeviceRecipe(deviceModel);
                } else {
                    initSecondClassify(recipeId);
                }
            } else {
                Log.e(TAG, "foodRecommond error");
            }

        }, throwable -> {
            Log.e(TAG, "foodRecommond查询失败: " + throwable.getMessage());
        });
    }

    /**
     * 取消收藏食谱
     *
     * @param favorateId
     */
    @SuppressLint("AutoDispose")
    private void cancelRecipeStored(int favorateId) {
        SearchFoodImpl.getInstance().cancleRecipeStore(favorateId).subscribe(result -> {
            if (result.isSuccess()) {
                if (!TextUtils.isEmpty(deviceModel)) {
                    getDeviceRecipe(deviceModel);
                } else {
                    initSecondClassify(recipeId);
                }
            } else {
                Log.e(TAG, "foodRecommond error");
            }

        }, throwable -> {
            Log.e(TAG, "foodRecommond查询失败: " + throwable.getMessage());
        });
    }

    @SuppressLint("AutoDispose")
    private void initNewRecomond() {
        recomondWord = getResources().getString(R.string.default_recomond);
        SearchFoodImpl.getInstance().getNewRecomond().subscribe(result -> {
            if (result.isSuccess()) {
                if (!TextUtils.isEmpty(result.data.rows.get(0).getRecipeName())) {
                    recomondWord = result.data.rows.get(0).getRecipeName();
                    clearEditText.setHint(recomondWord);
                }
                ;
            } else {
                Log.e(TAG, "initNewRecomond error" + result.message);
                clearEditText.setHint(recomondWord);
            }
        }, throwable -> {
            Log.e(TAG, "foodRecommond查询失败: " + throwable.getMessage());
            clearEditText.setHint(recomondWord);
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initRecycleView() {
        recipeTagsAdapter = new RecipeTagsAdapter(classifyList, RecipeTagsActivity.this, new RecipeTagsAdapter.onItemClickListener() {
            @Override
            public void OnItemClicked(int position) {
                originPage = 1;
                refreshLayout.setEnableLoadMore(true);
                recipeTagsAdapter.initPosition(position);
                originPosition = position;
                recipeId = classifyList.get(position).getClassificationId();
                mHotList.clear();
                hotAdapter.notifyDataSetChanged();
                initSecondClassify(recipeId);
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(RecipeTagsActivity.this);
        layoutManager.setOrientation(RecyclerView.HORIZONTAL);
        rvRecipeTitle.setLayoutManager(layoutManager);
        rvRecipeTitle.setAdapter(recipeTagsAdapter);
        rvRecipeTitle.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    rvRecipeDetail.postDelayed(runnable, 100);
                }

                if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_SETTLING) {
                    isUserControl = false;
                }

                int position = layoutManager.findFirstVisibleItemPosition();

            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_SETTLING && !isUserControl) {//自动滚动
                    //滚动幅度 在 -3 .. 3以内 其实时接近停止了 慢速滑动了 这时我们让他停止
                    if (dy >= -10 || dy <= 10) {//向下滚动
                        recyclerView.stopScroll();
                    }
                }
            }
        });
        if (classifyList.size() > 0) {
            recipeTagsAdapter.initPosition(originPosition);
            layoutManager.scrollToPosition(originPosition - 1);
        }

        hotAdapter = new RecipeHotAdapter(mHotList, RecipeTagsActivity.this);
        hotAdapter.setShowName(true);
        hotAdapter.setRecipeHotListener(new RecipeHotAdapter.OnClassifyClickListener() {
            @Override
            public void OnItemClick(int position) {
                RecipeHotBean bean = mHotList.get(position);
                AppAgent.startRecipePage(bean.getRecipeId(), bean.getModelId());
            }

            @Override
            public void OnItemLongClick(int position) {

            }

            @Override
            public void OnAvatarClick(int position) {
                RecipeHotBean hotBean = mHotList.get(position);
                if (!TextUtils.isEmpty(hotBean.getChefId())) {
                    Intent intent = new Intent(RecipeTagsActivity.this, CookerHomeActivity.class);
                    intent.putExtra(CHEF_ID, hotBean.getChefId());
                    startActivity(intent);
                } else {
                    ToastUtils.getInstance().showCustomToast(R.string.check_error);
                }
            }

            @Override
            public void OnStarClick(int position) {
                RecipeHotBean bean = mHotList.get(position);
                int state = bean.getFavoriteType();
                if (AppAgent.isLogin()) {
                    if (state == 1) {
                        cancelRecipeStored(bean.getFavoriteId());
                    } else {
                        RecipeStoreBean storeBean = new RecipeStoreBean();
                        storeBean.setAddrId(bean.getRecipeId());
                        storeBean.setFavoriteAddr("RECIPE_ID");
                        setRecipeStored(storeBean);
                    }
                } else {
                    SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
                }
            }

            @Override
            public void OnUnlikeRecipe(int position) {

            }

            @Override
            public void OnUnlikeClassify(int position) {

            }
        });
        rvRecipeDetail.setAdapter(hotAdapter);
        StaggeredGridLayoutManager staggeredGridLayoutManager =
                new StaggeredGridLayoutManager(2,
                        StaggeredGridLayoutManager.VERTICAL);

        rvRecipeDetail.setLayoutManager(staggeredGridLayoutManager);
        rvRecipeDetail.addItemDecoration(new GrideDecoration(RecipeTagsActivity.this, getResources().getDimensionPixelSize(R.dimen.dp_5)));
    }

    public Runnable runnable = () -> smoothScrollToPosition();

    private void smoothScrollToPosition() {
        isUserControl = true;
        View stickyInfoView = rvRecipeTitle.getChildAt(0); //获取头部View 第一个view
        int bottom = stickyInfoView.getRight();//获取view底部到rcy的顶部高度
        int height = stickyInfoView.getMeasuredWidth();//获取view高度
        if (bottom != height) {//去除正好停在正好的位置的情况
            if (bottom >= (height / 2)) {//判断view在上一半还是在下一半
                rvRecipeTitle.smoothScrollBy(-(height - bottom), 0);//二次滑动
            } else {
                rvRecipeTitle.smoothScrollBy(bottom, 0);//二次滑动
            }
        }
    }

    private void initClassifyData() {
        childListBean = (ChildListBean) getIntent().getExtras().get(CLASSIFY_SECOND_DATA);
        deviceModel = getIntent().getStringExtra(DEVICE_RECIPE);
        deviceName = getIntent().getStringExtra(DEVICE_RECIPE_NAME);
        if (TextUtils.isEmpty(deviceModel)) {
            initNewRecomond();
            if (childListBean != null) {
                ChildList childList = new ChildList();
                childList.setClassificationName(getResources().getString(R.string.recipe_all));
                childList.setClassificationId(childListBean.getClassificationId());
                classifyList.add(childList);
                classifyList.addAll(childListBean.getChildList());
                recipeId = classifyList.get(originPosition).getClassificationId();
                initSecondClassify(recipeId);
                toolbar.setTitle(childListBean.getClassificationName());
            } else {
                classifyList.clear();
            }
        } else {
            getDeviceRecipe(deviceModel);
            toolbar.setTitle(deviceName);
            classifyList.clear();
            rvRecipeTitle.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        int id = textView.getId();
        if (id == R.id.edt_common_search) {
            if (actionId == EditorInfo.IME_ACTION_SEND || (keyEvent != null && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                if (lastSearchTime != null) {
                    long temp = System.currentTimeMillis() - lastSearchTime;
                    if (temp < 1000) {
                        return true;
                    }
                }
                lastSearchTime = System.currentTimeMillis();
                String keywords = clearEditText.getText().toString().trim();
                if (!TextUtils.isEmpty(keywords)) {
                    initSearch(keywords);
                } else {
                    if (!TextUtils.isEmpty(recomondWord)) {
                        initSearch(recomondWord);
                    }
                }
                return true;
            }
        }
        return false;
    }

    private void setSoftInputMode(boolean visible) {
        if (visible) {
            if (getWindow() != null) {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            }
        } else {
            if (getWindow() != null) {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            }
        }
    }

    /**
     * 搜索详情页
     *
     * @param keyword
     */
    public void initSearch(String keyword) {
        clearEditText.setText(keyword);
        Intent intent = new Intent(RecipeTagsActivity.this, SearchResultActivity.class);
        intent.putExtra(SEARCH_KEYWORD, keyword);
        intent.putExtra(DEVICE_RECIPE, deviceModel);
        intent.putExtra(DEVICE_RECIPE_NAME, deviceName);

        startActivityForResult(intent, code);
        hideKeyboard(RecipeTagsActivity.this);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        clearEditText.setSelection(editable.length());
    }

    public static void hideKeyboard(Activity activity, View view) {
        if (activity != null) {
            if (view != null) {
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            } else {
                hideKeyboard(activity);
            }
        }
    }

    //关闭软键盘
    public static void hideKeyboard(Activity activity) {
        if (activity != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null && activity.getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
                if (null != activity.getCurrentFocus()) {
                    activity.getCurrentFocus().clearFocus();
                }
            }
        }
    }

    @Override
    protected void onPause() {
        setSoftInputMode(false);
        hideKeyboard(RecipeTagsActivity.this, clearEditText);
        super.onPause();
    }
}
